import logging
from peewee import fn
from playhouse.shortcuts import model_to_dict
from datetime import datetime
from api.db.db_models import seed_agent, data_rules
from api.db.services.common_service import CommonService

logger = logging.getLogger(__name__)

class seed_agentService(CommonService):
    model = seed_agent

    @classmethod
    def create_agent(cls, agent_data):
        try:
            # 检查必填字段
            if not agent_data.get('purpose'):
                raise ValueError("purpose不能为空")
            if not agent_data.get('data_source'):
                raise ValueError("data_source不能为空")
                
            agent = seed_agent.create(**agent_data)
            return model_to_dict(agent)
        except Exception as e:
            logger.error(f"创建Agent失败: {str(e)}", exc_info=True)
            raise ValueError(f"创建Agent失败: {str(e)}")

    @classmethod
    def delete_agent(cls, agent_id):
        try:
            query = seed_agent.delete().where(seed_agent.agent_id == agent_id)
            return query.execute() > 0
        except Exception as e:
            logger.error(f"删除Agent失败: {str(e)}")
            raise ValueError(f"删除Agent失败: {str(e)}")

    @classmethod
    def query_agents(cls, query_params):
        try:
            query = seed_agent.select()
            
            # 条件过滤
            if query_params.get('purpose'):
                query = query.where(seed_agent.purpose.contains(query_params['purpose']))
            if query_params.get('data_source'):
                query = query.where(seed_agent.data_source.contains(query_params['data_source']))
            if query_params.get('knowledge_base'):
                query = query.where(seed_agent.knowledge_base.contains(query_params['knowledge_base']))
            if query_params.get('importance_min'):
                query = query.where(seed_agent.importance >= query_params['importance_min'])
            if query_params.get('importance_max'):
                query = query.where(seed_agent.importance <= query_params['importance_max'])
            if query_params.get('start_timestamp'):
                query = query.where(seed_agent.create_time >= query_params['start_timestamp'])
            if query_params.get('end_timestamp'):
                query = query.where(seed_agent.create_time <= query_params['end_timestamp'])
            
            # 排序
            sort_field = query_params.get('sort_field', 'create_time')
            sort_order = query_params.get('sort_order', 'desc')
            
            if sort_field == 'importance':
                field = seed_agent.importance
            elif sort_field == 'create_date':
                field = seed_agent.create_date
            elif sort_field == 'update_date':
                field = seed_agent.update_date
            else:
                field = seed_agent.create_time
                
            if sort_order.lower() == 'asc':
                query = query.order_by(field.asc())
            else:
                query = query.order_by(field.desc())
            
            # 分页
            page = query_params.get('page', 1)
            per_page = query_params.get('per_page', 10)
            total = query.count()
            agents = query.paginate(page, per_page)
            
            return {
                'total': total,
                'page': page,
                'per_page': per_page,
                'list': [model_to_dict(agent) for agent in agents]
            }
        except Exception as e:
            logger.error(f"查询Agent失败: {str(e)}")
            raise ValueError(f"查询Agent失败: {str(e)}")
    
    @classmethod
    def update_agent(cls, agent_id, update_data):
        try:
            # 移除不能更新的字段
            update_data.pop('agent_id', None)
            update_data.pop('create_time', None)
            update_data.pop('create_date', None)
            
            query = seed_agent.update(**update_data).where(seed_agent.agent_id == agent_id)
            return query.execute() > 0
        except Exception as e:
            logger.error(f"更新Agent失败: {str(e)}")
            raise ValueError(f"更新Agent失败: {str(e)}")
    
    @classmethod
    def get_agent_detail(cls, agent_id):
        try:
            agent = seed_agent.get_or_none(seed_agent.agent_id == agent_id)
            if agent:
                return model_to_dict(agent)
            return None
        except Exception as e:
            logger.error(f"获取Agent详情失败: {str(e)}")
            raise ValueError(f"获取Agent详情失败: {str(e)}")

class data_rulesService(CommonService):
    model = data_rules

    @classmethod
    def create_rule(cls, rule_data):
        try:
            rule = data_rules.create(**rule_data)
            return model_to_dict(rule)
        except Exception as e:
            logger.error(f"创建DataRule失败: {str(e)}")
            raise ValueError(f"创建DataRule失败: {str(e)}")

    @classmethod
    def delete_rule(cls, rule_id):
        try:
            query = data_rules.delete().where(data_rules.rule_id == rule_id)
            return query.execute() > 0
        except Exception as e:
            logger.error(f"删除DataRule失败: {str(e)}")
            raise ValueError(f"删除DataRule失败: {str(e)}")

    @classmethod
    def get_rules_by_agent(cls, query_params):
        try:
            agent_id = query_params['agent_id']
            page = query_params.get('page', 1)
            per_page = query_params.get('per_page', 10)
            
            query = data_rules.select().where(data_rules.agent_id == agent_id)
            total = query.count()
            rules = query.paginate(page, per_page)
            
            return {
                'total': total,
                'page': page,
                'per_page': per_page,
                'list': [model_to_dict(rule) for rule in rules]
            }
        except Exception as e:
            logger.error(f"查询data_rules失败: {str(e)}")
            raise ValueError(f"查询data_rules失败: {str(e)}")
    @classmethod
    def update_rule(cls, rule_id, update_data):
        try:
            # 移除不能更新的字段
            update_data.pop('rule_id', None)
            update_data.pop('agent_id', None)
            update_data.pop('create_time', None)
            update_data.pop('create_date', None)
            
            query = data_rules.update(**update_data).where(data_rules.rule_id == rule_id)
            return query.execute() > 0
        except Exception as e:
            logger.error(f"更新DataRule失败: {str(e)}")
            raise ValueError(f"更新DataRule失败: {str(e)}")

    @classmethod
    def get_rule_detail(cls, rule_id):
        try:
            rule = data_rules.get_or_none(data_rules.rule_id == rule_id)
            if rule:
                return model_to_dict(rule)
            return None
        except Exception as e:
            logger.error(f"获取DataRule详情失败: {str(e)}")
            raise ValueError(f"获取DataRule详情失败: {str(e)}")
        
    @classmethod
    def batch_get_rules(cls, rule_ids):
        try:
            query = data_rules.select().where(data_rules.rule_id.in_(rule_ids))
            return [model_to_dict(rule) for rule in query]
        except Exception as e:
            logger.error(f"批量查询DataRules失败: {str(e)}")
            raise ValueError(f"批量查询DataRules失败: {str(e)}")